package leetcode.offer_two_special.binary;

import java.util.Random;

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(w);
 * int param_1 = obj.pickIndex();
 *
 * @author mazouri
 * @create 2021-09-21 13:07
 */
public class Solution {
    private int[] sums;
    public Solution(int[] w) {
        this.sums = w;
        for (int i = 1; i < w.length; i++) {
            sums[i]+=sums[i-1];
        }
    }

    public int pickIndex() {
        int random = new Random().nextInt(sums[sums.length - 1]);

//        for (int i = 0; i < sums.length; i++) {
//            //看落在那个区间[ )
//            if (random < sums[i]) return i;
//        }

        int left = 0;
        int right = sums.length;
        while (left<=right){
            int mid = (left+right)/2;

            if (sums[mid] > random){
                if (mid == 0 || sums[mid-1]<= random) return mid;

                right = mid-1;
            }else {
                left = mid+1;
            }
        }
        return 0;
    }
}
